<?php

class Controller_Newsletter extends Controller_Site
{
	private static function fields()
	{
		return array(
			'email' => array(
				'label' => 'Email',
				'validate' => 'required|valid_email'
			)
		);
	}
	public function action_signup()
	{
		if( Input::method() == 'POST' && Input::is_ajax() )
		{
			$email = trim(Input::post('email'));
			$val = Lib\Validate::forge();
			$val->add_fields(static::fields());

			if( !$val->run() )
			{
				Lib\Response::json(array(
					'status' => false,
					'alert' => $val->get_errors()
				), 1);
			}

			$find_item = DB::select(DB::expr('COUNT(*) as `total`'))
							->from('newsletters')
							->where('email', '=', $email)
							->as_object()->execute();
			if( $find_item[0]->total > 0 )
			{
				Lib\Response::json(array(
					'status' => true,
					'alert' => Lib\Message::error('Email is already exists')
				), 1);
			}
			$item = Model_Newsletter::forge(array(
				'created_at' => DB::expr('NOW()'),
				'ip_address' => Input::ip(),
				'user_agent' => Input::user_agent(),
				'email' => $email
			));

			if( !$item->save() )
			{
				Lib\Response::json(array(
					'status' => false,
					'alert' => Lib\Message::error('Server are busing')
				), 1);
			}
		}
	}
}